﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using University.Workshop.DataAccess;
using University.Workshop.Model;
using University.Workshop.Business;
using University.Workshop.WebApp.com.paypal.sandbox.www;

namespace University.Workshop.WebApp
{
    public partial class PaypalSuccess : System.Web.UI.Page
    {
        Product orderedProd = new Product();
        User Seller = new User();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                string token = Request.QueryString["token"];
                if (token == null)
                {
                    Response.Redirect("~/Default.aspx");
                }
                Collection<Product> prodList = Session["ProdList"] as Collection<Product>;
                DataTable prodTable = Session["ProdTable"] as DataTable;
                DataTable finalTable = Session["FinalTable"] as DataTable;
                if (prodList != null && finalTable != null && prodTable != null)
                {
                    var Id = Session["orderId"] is long ? (long) Session["orderId"] : 0;
                    var req = new GetExpressCheckoutDetailsReq()
                                  {
                                      GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType()
                                                                             {
                                                                                 Version = PaypalUtility.Version,
                                                                                 Token = token
                                                                             }
                                  };

                    // query PayPal for transaction details
                    GetExpressCheckoutDetailsResponseType resp =
                        PaypalUtility.BuildPayPalWebservice().GetExpressCheckoutDetails(req);
                    DoExpressCheckoutPaymentReq payReq = new DoExpressCheckoutPaymentReq();
                    payReq.DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType();
                    payReq.DoExpressCheckoutPaymentRequest.Version = PaypalUtility.Version;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails =
                        new DoExpressCheckoutPaymentRequestDetailsType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction =
                        PaymentActionCodeType.Sale;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentActionSpecified
                        = true;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.Token =
                        resp.GetExpressCheckoutDetailsResponseDetails.Token;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction =
                        PaymentActionCodeType.Sale;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PayerID =
                        resp.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails =
                        new PaymentDetailsType[1];
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0] =
                        new PaymentDetailsType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                        PaymentDetailsItem = new PaymentDetailsItemType[prodList.Count + 2];
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                        OrderTotal = new BasicAmountType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                        OrderTotal.currencyID = CurrencyCodeType.USD;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                        OrderTotal.Value = finalTable.Rows[2][1].ToString();

                    System.Globalization.CultureInfo cultureUS = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                        // .CurrentCulture

                    for (int i = 0; i < prodList.Count; i++)
                    {
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i] = new PaymentDetailsItemType();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Amount = new BasicAmountType();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Amount.currencyID = CurrencyCodeType.USD;
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Amount.Value = prodTable.Rows[i][2].ToString();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Name = prodTable.Rows[i][0].ToString();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Number = prodList[i].ProductId.ToString();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Quantity = prodTable.Rows[i][1].ToString();
                        payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[i].Description = "Order #" + Id.ToString();
                    }

                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].
                            PaymentDetailsItem[prodList.Count] = new PaymentDetailsItemType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Amount = new BasicAmountType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Amount.currencyID =
                        CurrencyCodeType.USD;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Amount.Value =
                        finalTable.Rows[0][1].ToString();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Name = "Taxes";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Number = "0";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Quantity = "1";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count].Description =
                        "Total taxes (5% of each product)";

                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1] = new PaymentDetailsItemType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Amount = new BasicAmountType();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Amount.currencyID =
                        CurrencyCodeType.USD;
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Amount.Value =
                        finalTable.Rows[1][1].ToString();
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Name = "Shipping";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Number = "0";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Quantity = "1";
                    payReq.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0].PaymentDetailsItem[prodList.Count + 1].Description =
                        "Total shipping (5$ per item)";

                    
                    try
                    {
                        DoExpressCheckoutPaymentResponseType doResponse = PaypalUtility.BuildPayPalWebservice().DoExpressCheckoutPayment(payReq);
                        this.orderedProd = OrderDataAccess.ProductByOrderId(Id);
                        OrderDataAccess.CompleteOrder(Id);
                        lOrder.Text = "Order #" + Id + " completed successfully";

                        Seller = UserDataAccess.GetUserById(orderedProd.SellerId);
                        sellerMail.Text = Seller.ContactInformation.Email;

                        //CODE USE TO CHANGE STATUS TO UNAVAILABLE IN UserWishList Table WHEN THE PRODUCT IS BOUGHT

                        //gridView1 -> get the productId according to the OrderId
                        GridView1.DataSource = OrderDataAccess.GetProductIdByOrderId(Id);
                        GridView1.DataBind();
                        //gridView2 -> a list of all the productsId in WishList
                        GridView2.DataSource = UserWishListDataAccess.WishListProducts();
                        GridView2.DataBind();

                        Product prod = new Product();
                        prod.ProductId = Convert.ToInt64(GridView1.Rows[0].Cells[0].Text);
                        GridView3.DataSource = ProductDataAccess.ViewProductQuantity(prod.ProductId);
                        GridView3.DataBind();
                        prod.Quantity = Convert.ToInt16(GridView3.Rows[0].Cells[0].Text);
                        foreach (GridViewRow row in GridView2.Rows)
                        {
                            if (GridView1.Rows[0].Cells[0].Text == row.Cells[0].Text)
                            {
                                if (prod.Quantity < 1)
                                {
                                    ChangeProductStatusbyOrderId(Id, GridView1);
                                    break;
                                }
                            }

                        }
                        //END CODE USE TO CHANGE STATUS TO UNAVAILABLE IN UserWishList Table WHEN THE PRODUCT IS BOUGHT

                        //CODE TO CHECK IF THE PRODUCT BOUGHT IS A GIFT CARD
                        bool IsProdGiftCard = IsGiftCard(Id);
                        if (IsProdGiftCard)
                        {
                            this.GiveButton.Visible = true;
                            this.KeepButton.Visible = true;
                            this.giftCardLabel.Text = "You Have bought a Gift Card!!";
                            this.GiveButton.Text = "Give it to";
                            this.KeepButton.Text = "Keep it for myself";
                        }
                        //else
                        //Response.AddHeader("REFRESH", "5;URL=Default.aspx");


                        //END CODE TO CHECK IF THE PRODUCT BOUGHT IS A GIFT 
                

                       

                    }
                    catch (Exception ex)
                    {
                        lOrder.Text = ex.Message;
                    }
                }

               
            }
        }

        public static void ChangeProductStatusbyOrderId(long orderId,GridView gr)
        {
            
            foreach (GridViewRow row in gr.Rows)
            {
                UserWishListDataAccess.UpdateProductStatus(Convert.ToInt64(row.Cells[0].Text));
            }
        }

        private bool IsGiftCard(long orderId)
        {
            Product orderedProduct = OrderDataAccess.ProductByOrderId(orderId);
            bool isGiftCard = GiftCardManager.IsGiftCard(orderedProduct.Name);
            if (isGiftCard)
                return true;
            else
                return false;
        }

        protected void GiveButton_Click(object sender, EventArgs e)
        {
            long orderId = GetOrderId();
            Product orderedProduct = OrderDataAccess.ProductByOrderId(orderId);
            string res = "true";
            Response.Redirect("UseGiftCard.aspx?ToSomeElse=" + res + "&Quantity=" +orderedProduct.Price + "&Currency=" + orderedProduct.Currency);
        }

        protected void KeepButton_Click(object sender, EventArgs e)
        {
            long orderId = GetOrderId();
            Product orderedProduct = OrderDataAccess.ProductByOrderId(orderId);
            string res = "false";
            Response.Redirect("UseGiftCard.aspx?ToSomeElse=" + res + "&Quantity=" +orderedProduct.Price + "&Currency=" + orderedProduct.Currency);
        }
        protected long GetOrderId()
        {
            return Session["orderId"] is long ? (long)Session["orderId"] : 0; 
        }

    }
}